<template>
  <div class="account">
    <el-form
      label-width="60px"
      size="large"
      :model="formAccount"
      :rules="rules"
      status-icon
      label-position="left"
      ref="ruleFormRef"
      style="max-width: 460px"
    >
      <el-form-item label="帐号" prop="uid">
        <el-input v-model="formAccount.uid" clearable />
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input type="password" clearable show-password v-model="formAccount.pwd" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs } from 'vue';
import type { FormRules, FormInstance } from 'element-plus';
import { IS_CHECKED, Account } from '@/global/constants';
import Storage from '@/utils/Storeage';
import useLoginStore from '@/store/login';

const loginStore = useLoginStore();
const formAccount = reactive({
  uid: Storage.get(Account)?.name ?? '',
  pwd: Storage.get(Account)?.password ?? ''
});

// 表单校验规则
const rules = reactive<FormRules>({
  uid: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    {
      pattern: /^\w{6,15}$/,
      message: '账号必须为6-20位,字母数字或下划线',
      trigger: 'blur'
    }
  ],
  pwd: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    {
      // 强密码
      // pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,12}$/,
      pattern: /^\w{4,12}$/,
      message: '账号必须为4-12位包含大小写字母和数字的组合,可以使用特殊字符',
      trigger: 'blur'
    }
  ]
});

// 表单ref
const ruleFormRef = ref<FormInstance>();

// 提交事件
const submitForm = () => {
  // validata 对某个字段进行校验 valid返回布尔值
  ruleFormRef?.value?.validate(async (valid) => {
    if (valid) {
      // 获取我们的账户密码
      const { uid, pwd } = toRefs(formAccount);
      loginStore.getLoginAction({ name: uid.value, password: pwd.value });
      if (Storage.get(IS_CHECKED)) {
        Storage.set(Account, { name: uid.value, password: pwd.value });
      } else {
        Storage.remove(Account);
      }
    } else {
      return false;
    }
  });
};

defineExpose({
  submitForm
});
</script>

<style lang="less" scoped></style>
